//
//  GSYOtherViewController.m
//  GoTraveling
//
//  Created by dllo on 15/12/23.
//  Copyright © 2015年 开发华佗. All rights reserved.
//

#import "GSYOtherViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "GSYResources.h"
#import "GSYOther.h"
#import "GSYOtherCollectionViewCell.h"
#import "GSYOtherDetailViewController.h"

@interface GSYOtherViewController ()<CLLocationManagerDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,GSYOtherCollectionViewCellDelegate>

@property (nonatomic,strong)CLLocationManager *manager;

@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)UIScrollView *scrollView;

@property (nonatomic,strong)NSMutableArray *btnArray;

@property (nonatomic,strong)UIView *selectView;

@property (nonatomic,strong)UIButton *beforeButton;

@property (nonatomic, retain) NSMutableArray *isLoad;

@property (nonatomic, retain) NSMutableDictionary *otherDic;

@property (nonatomic, retain) NSMutableArray *keyArray;

@property (nonatomic, retain) UIColor *textColor;

@property (nonatomic, retain) MBProgressHUD *mbBarPrpgressV;

@property (nonatomic, assign) CGPoint location;

@end

@implementation GSYOtherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"附近";
    
    _otherArray = [NSMutableArray array];
    
    self.textColor = [UIColor redColor];
    
    //地点类型
    self.otherDic = [NSMutableDictionary dictionary];
    //判断是否加载
    self.isLoad = [NSMutableArray array];
    //地点类型
    self.keyArray = [NSMutableArray arrayWithObjects:@"0", @"11", @"10", @"5", @"21", @"6", nil];
    for (NSString *temp in self.keyArray) {
        [self.isLoad addObject:@"0"];
        [self.otherDic setObject:[NSMutableArray array] forKey:temp];
    }

    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],UITextAttributeTextColor,nil]];
    
    
    self.navigationController.navigationBar.translucent = NO;
    
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.18 green:0.21 blue:0.24 alpha:1];
    
    //返回按钮

    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"icon_nav_back_button"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(leftButtonAction:)];
    
//    创建scrollview
    
    [self createScrollView];
    
    
//    创建collectionView
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT-94);
    
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    flowLayout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 30, WIDTH, HEIGHT-94) collectionViewLayout:flowLayout];
    
    self.collectionView.backgroundColor = self.view.backgroundColor;
    
    self.collectionView.pagingEnabled = YES;
    
    self.collectionView.delegate = self;
    
    self.collectionView.dataSource = self;
    
     [self.collectionView registerClass:[GSYOtherCollectionViewCell class] forCellWithReuseIdentifier:@"otherItem"];
    
    [self.view addSubview:self.collectionView];
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    
    
//    接受上一个页面传过来的值 功能：点击哪个进来的页面就是哪个
    NSIndexPath *index = [NSIndexPath indexPathForRow:self.initNum inSection:0];
    
    [self.collectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
    
    
//    定位
    
    self.manager = [[CLLocationManager alloc]init];
    
    self.manager.delegate =self;
    
    self.manager.distanceFilter = 10;
    
//    精度
    
    self.manager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    
//    开始定位
    
    [self.manager startUpdatingLocation];
    
//    程序运行时就会定位
    
    [self.manager requestAlwaysAuthorization];
    
    
    
    
    
}
-(void)createScrollView
{


    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, 30)];
    
    self.scrollView.backgroundColor = [UIColor whiteColor];
    
    self.scrollView.contentSize = CGSizeMake(WIDTH*1.2, 30);
    
    self.scrollView.scrollEnabled = NO;
    
    [self.view addSubview:self.scrollView];
    
    self.btnArray = [NSMutableArray array];
    
    NSArray *array = [NSArray arrayWithObjects:@"全部",@"景点",@"住宿",@"餐饮",@"娱乐",@"购物", nil];
    
    for (int i = 0; i<6; i++) {
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        
        button.frame = CGRectMake(WIDTH/5 *i, 5, WIDTH/5, 20);
        
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        button.titleLabel.font = [UIFont boldSystemFontOfSize:14];
        
        [button setTitle:array[i] forState:UIControlStateNormal];
        
        button.tag = 1000+i;
        
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:button];
        
        [self.btnArray addObject:button];
        
        
    }
    
    
    self.selectView = [[UIView alloc]initWithFrame:CGRectMake(WIDTH/5, 30-3, WIDTH/5, 3)];
    
    self.selectView.backgroundColor = [UIColor colorWithRed:0.156 green:0.803 blue:0.607 alpha:1.000];
    
    [self.scrollView addSubview:self.selectView];
    
    
}
#pragma mark 定位
//定位的代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    CLLocation *location = [locations lastObject];
    
    CLLocationCoordinate2D coordinate = location.coordinate;
    
    self.location = CGPointMake(coordinate.latitude, coordinate.longitude);
    
    [self setSelectNum:self.initNum];
    
//    停止
    
    [self.manager stopUpdatingLocation];


}

#pragma mark - 导航按钮点击事件
-(void)buttonAction:(UIButton *)btn
{

    if (![btn isEqual:self.beforeButton]) {
        
//        判断当前的区是否请求过网络
        
        if ([[self.isLoad objectAtIndex:btn.tag - 1000]isEqualToString:@"0"]) {
            
            [self AFNWorkingWithCategory:[self.keyArray objectAtIndex:btn.tag-1000]];
            
             [self.isLoad replaceObjectAtIndex:btn.tag - 1000 withObject:@"1"];
            
          
        }
        
//          设置scrollview的偏移量
        
        if (btn.tag == 1004 && self.scrollView.contentOffset.x == 0) {
            
            [self.scrollView setContentOffset:CGPointMake(WIDTH/5, 0) animated:YES];
            
        }
        
        if (btn.tag == 1001 && self.scrollView.contentOffset.x ==WIDTH/5) {
            
            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
            
        }
        
        
//        设置button大小和滑块位置
        
        NSIndexPath *index = [NSIndexPath indexPathForRow:btn.tag -1000 inSection:0];
        
        [self.collectionView scrollToItemAtIndexPath:index atScrollPosition:UICollectionViewScrollPositionRight animated:YES];
        
        [self.beforeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        CGRect frame = self.selectView.frame;
        
        frame.origin.x = btn.frame.origin.x;
        
        [UIView animateWithDuration:0.2 animations:^{
           
            self.selectView.frame = frame;
            
            self.beforeButton.transform = CGAffineTransformMakeScale(1, 1);
            
            btn.transform = CGAffineTransformMakeScale(1.15, 1.15);
        
        }];
        
        [btn setTitleColor:self.textColor forState:UIControlStateNormal];
        
        self.beforeButton = btn;
        
        
    }



}

#pragma mark 设置导航
- (void)setSelectNum:(NSInteger)selectNum {

    //判断当前的区是否请求过数据
    if ([[self.isLoad objectAtIndex:selectNum] isEqualToString:@"0"]) {
        
        [self AFNWorkingWithCategory:[self.keyArray objectAtIndex:selectNum]];
        
        [self.isLoad replaceObjectAtIndex:selectNum withObject:@"1"];
    }

     UIButton *button = [self.btnArray objectAtIndex:selectNum];
    
    if (![button isEqual:self.beforeButton]) {
        
        if (button.tag >= 1004 && self.scrollView.contentOffset.x == 0) {
            
            [self.scrollView setContentOffset:CGPointMake(WIDTH/ 5, 0) animated:YES];
        }
        if (button.tag <= 1001 && self.scrollView.contentOffset.x == WIDTH / 5) {
            
            [self.scrollView setContentOffset:CGPointMake(0, 0) animated:YES];
        }
        
        [self.beforeButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        
        CGRect frame = self.selectView.frame;
        
        frame.origin.x = button.frame.origin.x;
        
        [UIView animateWithDuration:0.2 animations:^{
            
            self.selectView.frame = frame;
            
            self.beforeButton.transform = CGAffineTransformMakeScale(1, 1);
            
            button.transform = CGAffineTransformMakeScale(1.15, 1.15);
            
        }];
        
        [button setTitleColor:self.textColor forState:UIControlStateNormal];
        
        self.beforeButton = button;
    }


}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{

    NSInteger index = scrollView.contentOffset.x /WIDTH;
    
    [self setSelectNum:index];

}
#pragma mark - AFN网络请求
- (void)AFNWorkingWithCategory:(NSString *)category {
    
    
    self.mbBarPrpgressV = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self.mbBarPrpgressV show:YES];
    
    NSString *strUrL = [NSString stringWithFormat:@"http://api.breadtrip.com/place/pois/nearby/?keyword=&category=%@&start=0&count=20&latitude=%f&longitude=%f", category, self.location.x, self.location.y];
    
    [GSYResources getDataWithName:strUrL block:^(id result) {
        
         NSDictionary *bigDic = result;
        
        _otherArray = [self.otherDic objectForKey:category];
        
        for (NSDictionary *dic in [bigDic objectForKey:@"items"]) {
            
            GSYOther *other = [[GSYOther alloc]init];
            
            [other setValuesForKeysWithDictionary:dic];
            
            [_otherArray addObject:other];
            
        }
        
        [self.mbBarPrpgressV hide:YES];
        
        [self.collectionView reloadData];

        
        
        
        
    } error:^{
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"网络连接错误" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [self.mbBarPrpgressV hide:YES];
        }];
        [alert addAction:action];
        
        [self presentViewController:alert animated:YES completion:nil];
    }];

        
        
    
}
-(void)leftButtonAction:(UIBarButtonItem *)btn
{

  [self dismissViewControllerAnimated:YES completion:^{
      
      
  }];



}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{

    return 1;

}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{

    return 6;


}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{

    static NSString *cellIdentifier = @"otherItem";
    
    GSYOtherCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    
    cell.otherArray = [self.otherDic objectForKey:self.keyArray[indexPath.row]];
    
    cell.delegates = self;
        
    cell.contentView.backgroundColor = self.view.backgroundColor;

    return cell;


}
-(void)pushDetailViewController:(NSString *)ID
{


    GSYOtherDetailViewController *detailVC = [[GSYOtherDetailViewController alloc]init];
    
    
    [self.navigationController pushViewController:detailVC animated:YES];



}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
